package cn.bonoon.handler.impl;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.bonoon.core.plugins.LoginRecordService;

@Component
public class LogonSessionListener extends ContextLoaderListener implements HttpSessionListener, ServletContextListener {

	@Override
	public void sessionCreated(HttpSessionEvent se) {
		// TODO Auto-generated method stub
		// ApplicationContext context = WebApplicationContextUtils
		// .getWebApplicationContext(se.getSession().getServletContext());
		// LoginRecordService loginRecordSevice = context
		// .getBean(LoginRecordService.class);
		// System.out.println("dddd");
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		try {
			ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(se.getSession().getServletContext());
			LoginRecordService loginRecordSevice = context.getBean(LoginRecordService.class);
			String sessionId = se.getSession().getId();
			loginRecordSevice.logout(sessionId);
		} catch (Throwable err) {
			// 忽略所有异常情况
			err.printStackTrace();
		}
	}

	// 服务器启动
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		try {
			ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
			LoginRecordService loginRecordSevice = context.getBean(LoginRecordService.class);
			loginRecordSevice.allLogout();
		} catch (Throwable err) {
			// 忽略所有异常情况
			err.printStackTrace();
		}
	}

	/**
	 * 服务器停止时，所有登录记录都将退出。
	 */
	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		try {
			// ApplicationContext context = WebApplicationContextUtils
			// .getWebApplicationContext(sce.getServletContext());
			// LoginRecordService loginRecordSevice = context
			// .getBean(LoginRecordService.class);
			// loginRecordSevice.allOut();
		} catch (Throwable err) {
			// 忽略所有异常情况
			err.printStackTrace();
		}
	}
}
